<template>
    <div class="main-container">
      <el-form ref="createForm" :model="taskData" :rules="rules">
        <!-- 基本配置 -->
        <div class="data-show">
          <div class="data-actions">
            <h3>基本配置</h3>
          </div>
          <div class="data-table">
            <div class="common-row row-between">
              <div class="common-item item-3">
                <label class="condition-label">算法名称</label>
                <el-form-item class="condition-input" prop="name">
                  <el-input type="text" placeholder="请输入算法名称" v-model="taskData.name" />
                </el-form-item>
              </div>
              <div class="common-item item-3">
                <label class="condition-label">嵌入文件名</label>
                <el-form-item class="condition-input" prop="embName">
                  <el-input type="text" placeholder="请输入嵌入文件名称" v-model="taskData.embName" />
                </el-form-item>
              </div>
              <div class="common-item item-3">
                <label class="condition-label">提取文件名</label>
                <el-form-item class="condition-input" prop="extName">
                  <el-input type="text" placeholder="请输入提取文件名称" v-model="taskData.extName" />
                </el-form-item>
              </div>
            </div>
            <div class="common-row row-between">
              <div class="common-item item-5">
                <label class="condition-label">算法平台</label>
                <el-form-item class="condition-input radio-input" prop="system">
                  <el-radio @change="systemChange" v-for="(item, index) in systems" :key="index" :label="item.name" :value="item.id" v-model="taskData.system">
                    <span>{{ item.name }}</span>
                  </el-radio>
                </el-form-item>
              </div>
              <div class="common-item item-5">
                <label class="condition-label">高级模式</label>
                <el-form-item class="condition-input radio-input" prop="isAdvance">
                  <el-radio @change="advanceChange" v-for="(item, index) in advances" :key="index" :label="item.label" :value="item.value" v-model="taskData.isAdvance">
                    <span>{{ item.label }}</span>
                  </el-radio>
                </el-form-item>
              </div>
            </div>
            <div class="common-row">
              <div class="common-item item-10">
                <label class="condition-label">算法描述</label>
                <el-form-item class="condition-input" prop="description">
                  <el-input v-model="taskData.description" maxlength="100" type="textarea" show-word-limit rows="4" resize="none" placeholder="请输入算法描述" />
                </el-form-item>
              </div>
            </div>
          </div>
        </div>
        <transition :name="stepTransition" mode="out-in">
          <div class="data-show" :key="currentStep.key">
            <div class="data-actions">
              <h3>算法组合</h3>
            </div>
            <div class="data-table data-table-step">
              <h3 class="algo-title">{{ currentStep.title }}</h3>
              <div class="algo-options">
                <el-radio @change="stepChange" v-model="currentStep.select" :disabled="item.disabled" v-for="(item, index) in currentStep.options" :key="index" :label="item.label" :value="item.value"></el-radio>
              </div>
              <div class="btn-container">
                <div class="btns">
                  <button :disabled="currentStep.key === 'one'" type="button" class="btn" @click="handlePrevious">上一步</button>
                  <button :disabled="((currentStep.key === 'four' || currentStep.key === 'seven') && currentStep.select && taskData.isAdvance === 0) || taskData.stepFinished" type="button" class="btn" @click="handleNext">下一步</button>
                </div>
              </div>
            </div>
          </div>
        </transition>
        <transition name="upload" mode="out-in">
          <div v-if="taskData.isAdvance === 1 && taskData.stepFinished && currentModuleLib">
            <transition :name="moduleTransition" mode="out-in">
              <SelectList
                isCondition
                changable
                :key="currentModuleLib.key"
                :count-all="currentModuleLib.countAll"
                :count-current="currentModuleLib.countCurrent"
                :count-un-set="currentModuleLib.countUnSet"
                :is-set="!!currentModuleLib.select"
                pre-title="模块静态库选择"
                :title="currentModuleLib.isDef == 1 ? `${currentModuleLib.moduleLibName}(默认)` : currentModuleLib.moduleLibName"
                :loading="currentModuleLib.condition.loading"
                :list="currentModuleLib.list"
                :condition="currentModuleLib.condition"
                :condition-list="currentModuleLib.conditionList"
                v-model:selectId="currentModuleLib.select"
                @get-more="getModuleByLib(currentModuleLib)"
                @handle-select="moduleSelect"
                @previous="previousModuleLib"
                @next="nextModuleLib"
                @del-condition="delCondition"
              >
                <template #data-condition>
                  <el-form :model="currentModuleLib.condition" size="small">
                    <div class="conditions-item">
                      <label class="condition-label">标题搜索：</label>
                      <el-form-item class="condition-form-item">
                        <el-input 
                          clearable
                          size="default"
                          class="condition-input" 
                          v-model="currentModuleLib.condition.name" 
                          placeholder="请输入模块名称"
                          @keydown.native.enter.prevent="conditionGetModules(currentModuleLib, 'name', currentModuleLib.condition.name, currentModuleLib.condition.name)"
                          @change="conditionGetModules(currentModuleLib, 'name', $event, $event)" 
                        />
                      </el-form-item>
                    </div>
                    <div class="conditions-item">
                      <label class="condition-label">平台：</label>
                      <el-form-item class="condition-form-item">
                        <el-select 
                          class="condition-input" 
                          size="default"
                          v-model="currentModuleLib.condition.system" 
                          placeholder="请选择模块平台"
                          clearable
                          @change="conditionGetModules(currentModuleLib, 'system', $event, getShow($event, 'id', systems, 'name'))"
                        >
                          <el-option v-for="(item, index) in systems" :key="index" :label="item.name" :value="item.id" />
                        </el-select>
                      </el-form-item>
                    </div>
                    <div class="conditions-item">
                      <label class="condition-label">状态：</label>
                      <el-form-item class="condition-form-item">
                        <el-select 
                          class="condition-input" 
                          size="default"
                          v-model="currentModuleLib.condition.status" 
                          placeholder="请选择模块状态"
                          clearable
                          @change="conditionGetModules(currentModuleLib, 'status', $event, getShow($event, 'value', taskStatus, 'label'))"
                        >
                          <el-option v-for="(item, index) in taskStatus" :key="index" :label="item.label" :value="item.value" />
                        </el-select>
                      </el-form-item>
                    </div>
                  </el-form>
                </template>
              </SelectList>
            </transition>
          </div>
        </transition>
        <!-- 模块参数输入 -->
        <transition name="appear" mode="out-in">
          <div class="data-show" :key="currentModuleLib.key" v-if="taskData.isAdvance === 1 && currentModuleLib && currentModuleLib.select && currentModuleLib.moduleParams.parameters.length > 0">
            <div class="data-actions">
              <h3>{{`${currentModuleLib.moduleLibName}-参数配置` }}</h3>
            </div>
            <div class="data-table">
              <el-form v-show="currentModuleLib.moduleParams.parameters.length > 0" :ref="setModuleParamsRef" :model="currentModuleLib.moduleParams.parameterObj" :rules="currentModuleLib.moduleParams.rules">
                <el-row :gutter="20">
                  <el-col 
                    v-for="(item, index) in currentModuleLib.moduleParams.parameters" 
                    :span="getParameterSpan"
                    :key="index"
                    style="margin: 0 auto"
                  >
                    <div class="common-item">
                      <label class="condition-label">
                        <el-tooltip v-if="item.description" :disabled="!item.description" :content="item.descrition" placement="top" effect="dark">
                          <i class="iconfont icon-gantanhao2 parameter-des"></i>
                        </el-tooltip>
                        {{ item.parameterCode }}
                      </label>
                      <el-form-item class="condition-input" :prop="item.parameterCode">
                        <el-input-number v-if="item.parameterType === 1" type="number" :min="item.minValue ? item.minValue : 0" :max="item.maxValue ? item.maxValue : 0" placeholder="请输入参数数值" v-model.number="currentModuleLib.moduleParams.parameterObj[item.parameterCode]" />
                        <el-select v-else-if="item.parameterType === 0" v-model="currentModuleLib.moduleParams.parameterObj[item.parameterCode]" clearable placeholder="请选择参数值">
                          <el-option v-for="(it, ind) in currentModuleLib.moduleParams.parameterOptions[item.parameterCode]" :key="ind" :label="it" :value="it" />
                        </el-select>
                        <el-input v-else disabled v-model="currentModuleLib.moduleParams.parameterObj[item.parameterCode]" placeholder="请输入固定值" />
                      </el-form-item>
                    </div>
                  </el-col>
                </el-row>
              </el-form>
              <div class="params-empty" v-show="currentModuleLib.moduleParams.parameters.length < 1">
                <i class="iconfont icon-wushuju1 data-empty-icon"></i>
                <h3 class="data-empty">无可设置参数</h3>
              </div>
            </div>
          </div>
        </transition>
      </el-form>
      <SelectList
        isCondition
        :title="parameter.title"
        :loading="parameter.condition.loading"
        :list="parameter.list"
        :condition="parameter.condition"
        :condition-list="parameter.conditionList"
        v-model:selectId="taskData.userParamId"
        @get-more="getParameters"
        @del-condition="delParameterCondition"
      >
        <template #data-condition>
          <el-form :model="parameter.condition" size="small">
            <div class="conditions-item">
              <label class="condition-label">标题搜索：</label>
              <el-form-item class="condition-form-item">
                <el-input 
                  clearable
                  size="default"
                  class="condition-input" 
                  v-model="parameter.condition.name" 
                  placeholder="请输入参数名称"
                  @keydown.native.enter.prevent="conditionGetParameters('name', parameter.condition.name,parameter.condition.name)"
                  @change="conditionGetParameters('name', $event, $event)" 
                />
              </el-form-item>
            </div>
          </el-form>
        </template>
      </SelectList>
      <div class="btn-groups" v-if="isBtnGroupsShow && taskData.isAdvance === 1">
        <button type="button" class="btn btn-normal" @click="back">取消</button>
        <button type="button" class="btn" @click="handleCreate">确定</button>
      </div>
      <div class="btn-groups" v-if="notAdvanceBtnGroupShow && taskData.isAdvance === 0">
        <button type="button" class="btn btn-normal" @click="back">取消</button>
        <button type="button" class="btn" @click="handleCreate">确定</button>
      </div>
    </div>
  </template>
  <script setup>
  import SelectList from '@/components/SelectList.vue';
  import useAppStore from '@/stores/app';
  import * as rule from '@/utils/rules.js';
  import * as request from '@/api/algo.js';
  import { getParameterList } from '@/api/parameter.js';
  import { getModuleAlgosParams } from '@/api/module.js';
  import { api } from '@/utils/status.js';
  import { deepCopy } from '@/utils/utils.js';
  import { ElMessage } from 'element-plus';
  import { ref, computed, onActivated, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  
  const defaultOptions = {
    one: [
      { value: '110001', label: 'MP4' },
      { value: '110002', label: 'MKV' },
      { value: '110003', label: 'AVI' }
    ],
    two: [
      { value: '210001', label: '是' },
      { value: '210002', label: '否' }
    ],
    three: [
      { value: '220001', label: 'YouTube' },
      { value: '220002', label: '抖音' }
    ],
    four: [
      { value: '230001', label: '先验优选策略' },
      { value: '230002', label: 'PCA优选策略' }
    ],
    // 全部的
    five: [
      { value: '310001', label: 'x264' },
      { value: '310002', label: 'x265' }
    ],
    // 是JPEG 不是鲁棒
    six: [
      { value: '410001', label: '运动向量域' },
      { value: '410002', label: '帧内预测模式域' },
      { value: '410003', label: '帧间预测模式域' },
      { value: '410004', label: '变换系数域' },
      { value: '410005', label: '伴音域' }
    ],
    // 是JPEG 是鲁棒
    seven: [
      { value: '510001', label: '哈夫曼码字' },
      { value: '510002', label: '编码系数' },
      { value: '510003', label: '快速' },
      { value: '510004', label: '安全' }
    ],
		sevenA: [
			{ value: '510001', label: '哈夫曼码字' },
      { value: '510002', label: '编码系数' }
		],
		sevenB: [
			{ value: '510003', label: '快速' },
      { value: '510004', label: '安全' }
		]
  };
  const systems = api.common.systems;
  const taskStatus = api.common.status;
  const advances = api.algo.advances;
  const rules = {
    name: [{ validator: rule.verifyObj.chineseReg, trigger: ['blur', 'change'] }],
    embName: [
      { min: 1, max: 32, message: '文件名不应超过32个字符', trigger: ['blur', 'change']},
      { validator: rule.verifyObj.chineseReg, trigger: ['blur', 'change'] }
    ],
    extName: [
      { min: 1, max: 32, message: '文件名不应超过32个字符', trigger: ['blur', 'change']},
      { validator: rule.verifyObj.chineseReg, trigger: ['blur', 'change'] }
    ],
    system: rule.createRequiredRule('算法平台不能为空'),
    isAdvance: rule.createRequiredRule('请选择是否使用高级模式')
  };
  // ============> data
  const router = useRouter();
  const appStore = useAppStore();

  
  const createForm = ref(null);
  const taskData = ref({
    isAdvance: 0,
    stepFinished: false,
    createFlag: false,
    name: '',
    embName: '',
    extName: '',
    system: null,
    userParamId: null,
    linkMoudleIds: [],
    description: '',
    optIds: [],
    moduleParams: []
  });
  const stepTransition = ref('stepright');
  const steps = ref({
    one: {
      key: 'one',
      select: null,
      title: '选择支持载体格式类型',
      options: []
    },
    two: {
      key: 'two',
      select: null,
      title: '是否支持社交网络信道鲁棒隐写',
      options: []
    },
    three: {
      key: 'three',
      select: null,
      title: '选择信道',
      options: []
    },
    four: {
      key: 'four',
      select: null,
      title: '选择鲁棒视频隐写算法',
      options: []
    },
    five: {
      key: 'five',
      select: null,
      title: '选择编码器类型',
      options: []
    },
    six: {
      key: 'six',
      select: null,
      title: '选择嵌入域',
      options: []
    },
    seven: {
      key: 'seven',
      select: null,
      title: '选择调制模式',
      options: []
    }
  })
  const currentStep = ref(null);
  // 算法参数对象
  const parameter = ref({
    condition: {
      name: '',
      loading: false,
      pageSize: api.common.pageSize,
      pageNumber: 0,
      totalRow: 0
    },
    conditionList: [],
    list: [],
    select: null,
    key: 'parameter',
    title: '用户参数选择'
  });
  // 组合算法对应的模块库列表
  const moduleLibs = ref([]);
  const currentModuleLib = ref(null);
  const moduleTransition = ref('stepright');
  const defaultModuleParams = {
  rules: {},
  parameterObj: {},
  parameterOptions: {},
  parameters: [],
  formRef: null
};

  // ============> computed
  const getShow = computed(() => {
    return function (v, k, arr, returnKey) {
      let obj = arr.find((item) => item[k] === v);
      let res = obj ? obj[returnKey] : "--";
      return res;
    };
  });
  const isBtnGroupsShow = computed(() => {
    let setModuleLib = moduleLibs.value.reduce((resArr, item) => {
      if (item.select) resArr.push(item.select);
      return resArr;
    }, []);
    let flag = ((currentStep.value.key === 'four' || currentStep.value.key === 'seven') && currentStep.value.select) && moduleLibs.value.length > 0 && setModuleLib.length == moduleLibs.value.length;
    return flag;
  });
  const notAdvanceBtnGroupShow = computed(() => {
  let flag = (currentStep.value.key === 'four' || currentStep.value.key === 'seven') && currentStep.value.select;
  return flag;
})
  const getParameterSpan = computed(() => {
    let parameterCount = currentModuleLib.value.moduleParams.parameters.length;
  let span;
  if (parameterCount === 1){
    span = 16;
  } else if (parameterCount % 2 === 0){
    span = 12;
  } else {
    span = 8;
  }
  return span;
});


  // ============> hooks
  for (let step in steps.value){
    steps.value[step].options = JSON.parse(JSON.stringify(defaultOptions[step]));
  }
  currentStep.value = steps.value.one;
  onMounted(() => {
    getParameters()
  })

  // ============> methods
  // 条件筛选参数列表
  function conditionGetParameters(conditionKey, conditionValue, conditionLabel){
    if (conditionValue !== null && conditionValue !== undefined && conditionValue !== ''){
      let conditionItem = parameter.value.conditionList.find(cond => cond.key === conditionKey);
      if (conditionItem) {
        conditionItem.value = conditionValue;
        conditionItem.label = conditionLabel;
      } else {
        parameter.value.conditionList.push({
          key: conditionKey,
          value: conditionValue,
          label: conditionLabel,
        });
      }
    } else {
      let conditionIndex = parameter.value.conditionList.findIndex(cond => cond.key === conditionKey);
      parameter.value.conditionList.splice(conditionIndex, 1);
    }
    parameter.value.condition.pageNumber = 0;
    parameter.value.condition.totalRow = 0;
    parameter.value.list = []
    getParameters();
  }
  // 点击参数列表筛选条件的关闭事件
  function delParameterCondition(conditionKey){
    parameter.value.condition[conditionKey] = null;
    let condIndex = parameter.value.conditionList.findIndex(cond => cond.key === conditionKey);
    parameter.value.conditionList.splice(condIndex, 1);
    parameter.value.condition.pageNumber = 0;
    parameter.value.condition.totalRow = 0;
    parameter.value.list = [];
    getParameters();
  }
  // 获取参数列表
function getParameters(){
  if (parameter.value.condition.pageNumber > 0 && parameter.value.list.length >= parameter.value.condition.totalRow) {
    return;
  }
  parameter.value.condition.pageNumber++;
  parameter.value.condition.loading = true;
  getParameterList(parameter.value.condition)
    .then(res => {
      if (res){
        parameter.value.list = parameter.value.list.concat(res.records);
        parameter.value.condition.pageNumber = res.pageNumber;
        parameter.value.condition.totalRow = res.totalRow;
      }
    })
    .catch(err => {
      console.log(err);
    })
    .finally(() => {
      parameter.value.condition.loading = false;
    })
}
 // 条件筛选参数列表
 function conditionGetModules(item, conditionKey, conditionValue, conditionLabel){
  if (conditionValue){
    let conditionItem = item.conditionList.find(cond => cond.key === conditionKey);
    if (conditionItem) {
      conditionItem.value = conditionValue;
      conditionItem.label = conditionLabel;
    } else {
      item.conditionList.push({
        key: conditionKey,
        value: conditionValue,
        label: conditionLabel,
      });
    }
  } else {
    let conditionIndex = item.conditionList.findIndex(cond => cond.key === conditionKey);
    item.conditionList.splice(conditionIndex, 1);
  }
  item.condition.pageNumber = 0;
  item.condition.totalRow = 0;
  item.list = [];
  getModuleByLib(item);
}
function delCondition(conditionKey){
  currentModuleLib.value.condition[conditionKey] = null;
  let condIndex = currentModuleLib.value.conditionList.findIndex(cond => cond.key === conditionKey);
  currentModuleLib.value.conditionList.splice(condIndex, 1);
  currentModuleLib.value.condition.pageNumber = 0;
  currentModuleLib.value.condition.totalRow = 0;
  currentModuleLib.value.list = [];
  getModuleByLib(currentModuleLib.value);
}
// 获取模块库对应的模块
function getModuleByLib(item){
  if (item.condition.pageNumber > 0 && item.list.length >= item.condition.totalRow){
    return;
  }
  item.condition.pageNumber++;
  item.condition.loading = true;
  getModuleAlgosParams(item.condition)
    .then(res => {
      if (res){
        item.list = item.list.concat(res.records);
        item.condition.pageNumber = res.pageNumber;
        item.condition.totalRow = res.totalRow;
      }
    })
    .catch(err => {
      console.log(err);
    })
    .finally(() => {
      item.condition.loading = false;
    })
}
// 模块库对应的模块选择事件
function moduleSelect(e){
  taskData.value.moduleParams = [];
  let unsetCount = moduleLibs.value.length;
  moduleLibs.value.forEach(item => {
    if (item.select){
      unsetCount--;
    }
  });
  moduleLibs.value.forEach(item => {
    item.countUnSet = unsetCount;
  });
  currentModuleLib.value.moduleParams = deepCopy(defaultModuleParams);
  let moduleItem = currentModuleLib.value.list.find(item => item.id === e);
  if (moduleItem && Array.isArray(moduleItem.moduleParams) && moduleItem.moduleParams.length > 0){
    createModuleParams(currentModuleLib.value, moduleItem.moduleParams);
  }
}
function previousModuleLib(){
  let countCurrent = currentModuleLib.value.countCurrent;
  if (countCurrent === 1) return;
  if (currentModuleLib.value.moduleParams.formRef && currentModuleLib.value.moduleParams.parameters.length > 0) {
    currentModuleLib.value.moduleParams.formRef.validate(valid => {
      if (valid){
        moduleTransition.value = 'stepleft';
        currentModuleLib.value = moduleLibs.value.find(item => item.countCurrent === (countCurrent-1))
      } else {
        ElMessage.warning('当前模块库参数填写有误， 请核对');
      }
    })
  } else {
    moduleTransition.value = 'stepleft';
    currentModuleLib.value = moduleLibs.value.find(item => item.countCurrent === (countCurrent-1))
  }
}
function nextModuleLib(){
  let countCurrent = currentModuleLib.value.countCurrent;
  if (countCurrent === moduleLibs.value.length) return;
  if (currentModuleLib.value.moduleParams.formRef && currentModuleLib.value.moduleParams.parameters.length > 0){
    currentModuleLib.value.moduleParams.formRef.validate(valid => {
      if (valid){
        moduleTransition.value = 'stepright';
        currentModuleLib.value = moduleLibs.value.find(item => item.countCurrent === (countCurrent+1))
      } else {
        ElMessage.warning('当前模块库参数填写有误， 请核对');
      }
    })
  } else {
    moduleTransition.value = 'stepright';
    currentModuleLib.value = moduleLibs.value.find(item => item.countCurrent === (countCurrent+1))
  }
}
function systemChange(){
  taskData.value.stepFinished = false;
  moduleLibs.value = [];
  currentModuleLib.value = null;
  taskData.value.moduleParams = [];
}
  // 点击上一步
  function handlePrevious(){
    currentStep.value.select = null;
    stepTransition.value = 'stepleft';
    taskData.value.stepFinished = false;
    moduleLibs.value = [];
    currentModuleLib.value = null;
    taskData.value.moduleParams = [];
		if (currentStep.value.key === 'seven'){
			currentStep.value = steps.value.six;
      return;
		}
		if (currentStep.value.key === 'six'){
			currentStep.value = steps.value.five;
      return;
		}
		if (currentStep.value.key === 'five'){
			currentStep.value = steps.value.two;
      return;
		}
		if (currentStep.value.key === 'four'){
			currentStep.value = steps.value.three;
      return;
		}
		if (currentStep.value.key === 'three'){
			currentStep.value = steps.value.two;
      return;
		}
		if (currentStep.value.key === 'two'){
			currentStep.value = steps.value.one;
      return;
		}
  }
  // 点击下一步
  function handleNext(){
    if (!currentStep.value.select){
      ElMessage.warning('当前流程未完成，请核对');
      return;
    }
    stepTransition.value = 'stepright';
    if (currentStep.value.key === 'one'){
      currentStep.value = steps.value.two;
			return;
    }
		if (currentStep.value.key === 'two' && currentStep.value.select == '210001'){
			currentStep.value = steps.value.three;
			return;
		} else if (currentStep.value.key === 'two' && currentStep.value.select == '210002') {
			currentStep.value = steps.value.five;
			return;
		}
		if (currentStep.value.key === 'three'){
			currentStep.value = steps.value.four;
			return;
		}
		if (currentStep.value.key === 'five'){
			currentStep.value = steps.value.six;
			return;
		}
		if (currentStep.value.key === 'six' && currentStep.value.select == '410005'){
			steps.value['seven'].options = JSON.parse(JSON.stringify(defaultOptions.sevenA));
			currentStep.value = steps.value.seven;
			return;
		} else if (currentStep.value.key === 'six' && currentStep.value.select != '410005') {
			steps.value['seven'].options = JSON.parse(JSON.stringify(defaultOptions.sevenB));
			currentStep.value = steps.value.seven;
			return;
		}
    // 选择步骤完成拉取模块
    if ((currentStep.value.key === 'four' || currentStep.value.key === 'seven') && currentStep.value.select && taskData.value.isAdvance === 1){
      getModuleLibs();
    }
  }
  // 步骤选择事件
  function stepChange(){
    moduleLibs.value = [];
    taskData.value.stepFinished = false;
    currentModuleLib.value = null;
    taskData.value.moduleParams = [];
  }
  function getModuleLibs(){
    if (!taskData.value.system) {
      ElMessage.warning('请先选择算法平台');
      return;
    }
    let optIds = [];
    for (let key in steps.value){
      if (steps.value[key].select){
        optIds.push(steps.value[key].select);
      }
    }
    request.getStepLibs({system: taskData.value.system, optIds})
      .then(res => {
        if (Array.isArray(res) && res.length > 0){
          moduleLibs.value = res;
          initModuleLibs();
        } else {
          ElMessage.error('获取步骤对应模块静态库失败，请稍后重试或联系管理员');
        }
      })
      .catch(err => {
        console.log(err);
      })
  }
  function initModuleLibs(){
    let promises = [];
    let countCurrent = 1;
    let countUnSet = moduleLibs.value.length;
    moduleLibs.value.forEach(moduleLib => {
      moduleLib.select = null;
      moduleLib.key = moduleLib.moduleLibId;
      moduleLib.condition = {
        name: '',
        system: taskData.value.system,
        status: null,
        moduleLibId: moduleLib.moduleLibId,
        loading: false,
        pageSize: api.common.pageSize,
        pageNumber: 1,
        totalRow: 0
      };
      moduleLib.countCurrent = countCurrent;
      countCurrent++;
      moduleLib.countAll = moduleLibs.value.length;
      moduleLib.conditionList = [];
      moduleLib.conditionList.push({
        key: 'system', 
        value: taskData.value.system, 
        label: getShow.value(taskData.value.system, 'id', systems, 'name')
      });
      moduleLib.list = [];
      // 为每个模块库初始化一个模块参数对象
      moduleLib.moduleParams = deepCopy(defaultModuleParams);
      promises.push(new Promise((resolve, reject) => {
      if (moduleLib.isDef === 1 && moduleLib.moduleId){
        countUnSet--;
        moduleLib.select = moduleLib.moduleId;
      }
      getModuleAlgosParams(moduleLib.condition)
        .then(res => {
          if (res){
            moduleLib.list = moduleLib.list.concat(res.records);
            moduleLib.condition.pageNumber = res.pageNumber;
            moduleLib.condition.totalRow = res.totalRow;
            // 如果有默认项找出默认的那一项 createModuleParams
            if (moduleLib.isDef === 1&& moduleLib.moduleId) {
              let moduleLibItem = moduleLib.list.find(it => it.id === moduleLib.select);
              if (moduleLibItem && Array.isArray(moduleLibItem.moduleParams) && moduleLibItem.moduleParams.length > 0){
                createModuleParams(moduleLib, moduleLibItem.moduleParams);
              }
            }
            resolve();
          } else {
            reject();
          }
        })
        .catch(err => {
          console.log(err)
          reject();
        })
    }));
    });
    moduleLibs.value.forEach(item => item.countUnSet = countUnSet );
    Promise.all(promises)
      .then(() => {
        taskData.value.stepFinished = true;
        currentModuleLib.value = moduleLibs.value[0];
      })
      .catch(err => {
        console.log(err)
      })
  }
  // 组装选择的算法id
  function getStepSelects(){
    let selects = [];
    for (let key in steps.value){
      if (steps.value[key].select){
        selects.push(steps.value[key].select);
      }
    }
    taskData.value.optIds = selects;
  }
  function advanceChange(e){
    moduleLibs.value = [];
    taskData.value.stepFinished = false;
    currentModuleLib.value = null;
    taskData.value.moduleParams = [];
  }
  function setModuleParamsRef(dom){
    if (dom){
      currentModuleLib.value.moduleParams.formRef = dom;
    }
  }
// 点击高级模式模块参数的创建按钮
function handleModuleParams(){
  let result = [];
  moduleLibs.value.forEach(moduleLib => {
    if (moduleLib.moduleParams.parameters.length > 0){
      moduleLib.moduleParams.parameters.forEach(item => {
        result.push({
          parameterCode: item.parameterCode,
          parameterValue: moduleLib.moduleParams.parameterObj[item.parameterCode]
        });
      })
    }
  });
  taskData.value.moduleParams = result;
}
  function handleCreate(){
    if (taskData.value.createFlag){
      ElMessage.warning('当前正在创建组合算法，请稍后');
      return;
    }
    if ((currentStep.value.key !== 'four' || currentStep.value.key !== 'seven') && !currentStep.value.select){
      ElMessage.warning('请先完成算法组合！');
      return;
    }
    if (!taskData.value.userParamId){
      ElMessage.warning('请选择用户参数！');
      return;
    }
    let linkMoudleIds = moduleLibs.value.reduce((resArr, item) => {
      if (item.select) resArr.push(item.select);
      return resArr;
    }, []);
    if (taskData.value.isAdvance === 1 && ((linkMoudleIds.length < moduleLibs.value.length) || linkMoudleIds.length == 0)){
      ElMessage.warning('请先完成所有静态库模块选择！');
      return;
    }
    createForm.value.validate(valid => {
      if (valid){
        taskData.value.createFlag = true;
        appStore.openLoading('组合算法创建中...');
        if (taskData.value.isAdvance === 1){
          taskData.value.linkMoudleIds = linkMoudleIds;
          handleModuleParams();
        }
        getStepSelects();
        request.createAlgo(taskData.value)
          .then(res => {
            ElMessage.success('创建算法成功!');
            router.replace({ name: 'algorithmManage' });
          })
          .catch(() => {
            taskData.value.optIds = [];
          })
          .finally(() => {
            taskData.value.createFlag = false;
            taskData.value.moduleParams = [];
            appStore.closeLoading();
          })
      } else {
        ElMessage.warning('当前提交项填写信息有误，请核对后提交');
        taskData.value.moduleParams = [];
      }
    })
  }
  function back(){
    router.back();
  }

  // 组装moduleParams
function createModuleParams(moduleLib, params){
  params.forEach(item => {
    if (item.parameterType === 0){
      moduleLib.moduleParams.parameterOptions[item.parameterCode] = item.enumValue.split(',');
      moduleLib.moduleParams.parameterObj[item.parameterCode] = item.parameterValue;
      moduleLib.moduleParams.rules[item.parameterCode] = rule.createRequiredRule(`${item.parameterCode}不能为空`);
    } else if (item.parameterType === 1){
      moduleLib.moduleParams.parameterObj[item.parameterCode] = +item.parameterValue;
      item.minValue = +item.minValue;
      item.maxValue = +item.maxValue;
      moduleLib.moduleParams.rules[item.parameterCode] = [{required: true, validator(rule, value, callback){
        if (value == undefined || value == null || value == ''){
          return callback(new Error(`${item.parameterCode}不能为空`));
        } else if (value < +item.minValue || value > +item.maxValue){
          return callback(new Error(`${item.parameterCode}值最小应为${+item.minValue}最大应为${+item.maxValue}`));
        } else {
          callback();
        }
      }, trigger: ['blur', 'change']}];
    } else if (item.parameterType === 2){
      moduleLib.moduleParams.parameterObj[item.parameterCode] = +item.parameterValue;
    }
    moduleLib.moduleParams.parameters.push(item);
  })
}
  </script>
  <style lang='scss' scoped>
  @import '@/assets/styles/mixin.scss';
  .algo-title {
    text-align: center;
    margin: 20px 0;
    color: var(--color-main);
    font-size: 18px;
  }
  .algo-options {
    @include flex-all-center;
    flex-direction: column;
    .el-radio {
      width: 60%;
      height: 40px;
      margin: 10px 0;
      border: 1px solid var(--color-main-border);
      background-color: var(--color-white-10);
      border-radius: 10px;
      transition: all 0.3s linear;
      text-align: center;
      justify-content: center;
    }
    .el-radio.is-checked {
      border: 1px solid var(--color-theme-border);
      background-color: var(--color-main);
      
      &::v-deep .el-radio__label {
        color: var(--color-white-10);
      }
    }
    .el-radio.is-disabled {
      cursor: not-allowed;
      background-color: var(--color-black-2);
      &.is-checked {
        background-color: var(--color-main-3)
      }
      &::v-deep .el-radio__label {
        color: var(--color-white-10);
      }
    }
    &::v-deep .el-radio__input {
      display: none;
    }
  }
  .btn-container {
    margin-top: 25px;
    @include flex-all-center;
    .btns {
      width: 60%;
      @include flex-between-center;
      .btn {
        width: 49%;
      }
    }
  }
  .data-table-step {
    position: relative;
    .next {
      position: absolute;
      top: 0;
      right: 0;
      height: 100%;
      width: 100px;
      background: linear-gradient(to right, var(--color-white-1), var(--color-main-3), var(--color-main-5), var(--color-main-7), var(--color-main));
      transition: all 0.4s ease;
      transform: translateX(50px);
      border-radius: 4px;
      cursor: pointer;
    }
    .next:hover {
      background: var(--color-main);
      transform: translateX(0);
      border: 1px solid var(--color-white-10);
    }
  }

  .table-actions {
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 100%;
  height: 100%;
  .action {
    width: 80px;
  }
}
.green {
  color: var(--color-green);
}
.red {
  color: var(--color-red);
  @include red-text-shadow;
}
.blue {
  color: var(--color-text-hover);
  @include blue-text-shadow;
}
.main-color {
  color: var(--color-main);
  @include main-text-shadow;
}
.params-empty {
  width: 100%;
  height: 180px;
  border: 2px solid var(--color-main);
  border-radius: 4px;
  background-color: var(--color-gray-5);
  @include inset-shadow-main-8;
  @include flex-all-center;
  flex-direction: column;
  .data-empty {
    color: var(--color-main);
    font-size: 20px;
  }
  // 无数据图标
  .data-empty-icon {
    color: var(--color-main);
    font-size: 80px;
  }
}
.parameter-des {
  color: var(--color-main);
  cursor: pointer;
  margin: 0 15px;
}
  </style>